# -*- coding:utf-8 -*- #

# ----------------------------------------------------------
# Name:        asyncQueueDemo
# Description: 异步io与queue  生产者 消费者
# Authon:      syl
# Date:        2020-12-11
# ----------------------------------------------------------

import asyncio
import queue
import time
import threading

end = False


def readfile(q, start=0):
    lines = []
    with open('asyncDemo.py', 'r', encoding='utf-8') as fr:
        lines = fr.readlines()
    lines = lines[start:]
    print('thread working')
    for i, l in enumerate(lines):
        q.put((start + i, l))
    global end
    end = True
    pass


async def getdata(c):
    await asyncio.sleep(0.5)
    return c.strip()


async def handler(q, i):
    global end
    ts = time.time()
    while not end or not q.empty():
        index, content = q.get()
        content = await  getdata(content)
        print(f"{i} index {index} {time.time() - ts} {content}")
    return f'{i} cost:{time.time() - ts}'


def main():
    start = 0
    q = queue.Queue()
    t = threading.Thread(target=readfile, args=(q, start,))
    t.start()

    task = [handler(q, i) for i in range(10)]
    loop = asyncio.get_event_loop()
    futures = loop.run_until_complete(asyncio.wait(task))

    t.join()

    for f in futures[0]:
        if f.done():
            print(f'{f.result()}')

    loop.close()
    pass


if __name__ == '__main__':
    ts = time.time()
    main()
    print(f'exit!!  {time.time() - ts}')
